from rest_framework.decorators import api_view
from ..utils.utils import *
from ..myModels.productModel import *
from ..myModels.categoryModel import *
from ..myModels.cartModel import *
import json
from django.core.paginator import Paginator

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi


@api_view(['get'])
def product_add(request):
    return info('添加商品')


# 通过json文件批量插入
def product_add_json(request):
    return success('暂停服务')

    # 项目从manage.py开始执行, 所以文件的读取是相对manage.py来写
    # with open('../data/product.json', 'r', encoding='utf-8') as json_file:
    with open('./fresh/data/product.json', encoding='utf-8') as json_file:
        # dumps和loads是在内存中转换（python对象和json字符串之间的转换），而dump和load则是对应于文件的处理。
        data = json.load(json_file)

        bulk_list = []
        for item in data:
            # 创建分类
            category = Category.objects.filter(
                name=item['categoryName']).first()
            # print(item['categoryName'])
            print(category.id)
            obj = {
                "category_id": category.id,
                "masterName": item['masterName'],
                "slaveName": item['slaveName'],
                "inventory": item['inventory'],
                "maxPrice": item['maxPrice'],
                "minPrice": item['minPrice'],
                "banners": ','.join(item['banners']),
                "descPics": ','.join(item['descPics']),
            }
            Product.objects.get_or_create(**obj)
            # bulk_list.append(Product(**obj))
            # Product.objects.bulk_create(bulk_list)
    return info([])


@api_view(['post'])
def product_all(request):
    values = Product.objects.all().values()
    res_list = []
    for item in values:
        obj = {
            **item,
            "banners": item['banners'].split(','),
            "descPics": item['descPics'].split(','),
            "maxPrice": float(item['maxPrice']),
            "minPrice": float(item['minPrice'])
        }
        res_list.append(obj)
    return success(res_list)


@api_view(['get'])
def product_detail(request):
    try:
        # 查询购物车数量
        user_id = request.session.get('session')
        if user_id:
            res_list = Cart.objects.filter(user_id=user_id).values()
            res_list = list(res_list)
            cartNum = 0
            for i in res_list:
                cartNum += i['buyNum']

        id = get_param(request, 'id')
        if not id:
            return fail('缺少id')
        product = Product.objects.filter(id=id).first()
        if not product:
            return fail('商品不存在')
        res_data = m_to_d(product)
        res_data['banners'] = res_data['banners'].split(',')
        res_data['descPics'] = res_data['descPics'].split(',')
        res_data['cartNum'] = cartNum
        return success(res_data)
    except Exception as e:
        return fail(str(e))


@swagger_auto_schema(method='get', manual_parameters=get_schema_prams([
    ('currPage', '当前页', openapi.TYPE_NUMBER or openapi.TYPE_STRING, False),
    ('pageSize', '每页条数', openapi.TYPE_NUMBER or openapi.TYPE_STRING, False),
    ('categoryId', '分类编号', openapi.TYPE_NUMBER or openapi.TYPE_STRING, False)
]),
    responses={
    200: 'ok',
    'currPage': '当前页',
    'pageSize': '每页条数',
    'msg': '信息',
    'data': '''[
                   {
                    "id": '商品编号',
                    "category_id": '分类编号',
                    "masterName": '商品名称',
                    "slaveName": '商品描述',
                    "inventory": '库存',
                    "maxPrice": '最高价格',
                    "minPrice": '最低价格',
                    "banners": '轮播图',
                    "descPics": '商品图片列表',
                    "imgUrl": '商品图片',
                }
    ]'''
}
)
@api_view(['get'])
def product_list(request):
    curr_page = get_param(request, 'currPage') or 1
    page_size = get_param(request, 'pageSize') or 7
    category_id = get_param(request, 'categoryId')
    # 根据分类编号进行查询
    if category_id:
        data = Product.objects.filter(category_id=category_id).values()
        data = list(data)
    else:
        data = Product.objects.all().values()[:20]
        try:
            paginator = Paginator(data, page_size)
            page_data = paginator.page(curr_page)
            data = list(page_data)
        except Exception:
            data = []

    res_list = handle_list(data)
    # return Response(res_list)
    return success(res_list, currPage=curr_page, pageSize=page_size)


def product_search(request):
    keyword = get_param(request, 'keyword')
    values = Product.objects.filter(masterName__contains=keyword).values()
    res_list = handle_list(list(values))
    return success(res_list)


# 处理商品列表
def handle_list(products):
    res_list = []
    for item in products:
        obj = {
            **item,
            "imgUrl": item['banners'].split(',')[0],
            # "descPics": item['descPics'].split(','),
            "maxPrice": float(item['maxPrice']),
            "minPrice": float(item['minPrice'])
        }
        res_list.append(obj)
    return res_list


@api_view(['get'])
def banners(request):
    return info({
        "code": 1,
        "msg": "success",
        "data": [
            "http://static.huruqing.cn/fresh/banner1.jpeg",
            "http://static.huruqing.cn/fresh/banner2.jpeg",
            "http://static.huruqing.cn/fresh/banner3.jpeg"
        ]
    })
